/**
 * AJAX File Upload
 * http://github.com/davgothic/AjaxFileUpload
 * 
 * Copyright (c) 2010-2013 David Hancock (http://davidhancock.co)
 *
 * Thanks to Steven Barnett for his generous contributions
 *
 * Licensed under the MIT license ( http://www.opensource.org/licenses/MIT )
 */

;(function($) {
	$.fn.AjaxFileUpload = function(options) {
		
		var defaults = {
			action:     "upload.php",
			send_data:     '', 
			onChange:   function(filename) {},
			onSubmit:   function(filename) {},
			onComplete: function(filename, response) {}
		},
		settings = $.extend({}, defaults, options),
		randomId = (function() {
			var id = 0;
			return function () {
				return "_AjaxFileUpload" + id++;
			};
		})();
		
		return this.each(function() {
			var $this = $(this);
			if ($this.is("input") && $this.attr("type") === "file") {
				$this.bind("change", onChange);
			}
		});
		
		function onChange(e) {
			var $element = $(e.target),
				id       = $element.attr('id'),
				$clone   = $element.removeAttr('id').clone().attr('id', id).AjaxFileUpload(options),
				filename = $element.val().replace(/.*(\/|\\)/, ""),
				iframe   = createIframe(),
				form     = createForm(iframe);

			// We append a clone since the original input will be destroyed
			$clone.insertBefore($element);

			settings.onChange.call($clone[0], filename);

			iframe.bind("load", {element: $clone, form: form, filename: filename}, onComplete);
			
			form.append($element).bind("submit", {element: $clone, iframe: iframe, filename: filename}, onSubmit).submit();
		}
		
		function onSubmit(e) {
			var data = settings.onSubmit.call(e.data.element, e.data.filename);
			// If false cancel the submission
			if (data === false) {
				// Remove the temporary form and iframe
				$(e.target).remove();
				e.data.iframe.remove();
				return false;
			} else {
				// Else, append additional inputs
				for (var variable in data) {
					alert(variable+"="+data[variable]);
					$("<input />")
						.attr("type", "hidden")
						.attr("name", variable)
						.val(data[variable])
						.appendTo(e.target);
				}
			}
		}
		
		function onComplete (e) {
			var $iframe  = $(e.target),
				doc      = ($iframe[0].contentWindow || $iframe[0].contentDocument).document,
				response = doc.body.innerHTML;

			if (response) {
				response = $.parseJSON(response);
			} else {
				response = {};
			}

			settings.onComplete.call(e.data.element, e.data.filename, response);
			
			// Remove the temporary form and iframe
			e.data.form.remove();
			$iframe.remove();
		}

		function createIframe() {
			var id = randomId();

			// The iframe must be appended as a string otherwise IE7 will pop up the response in a new window
			// http://stackoverflow.com/a/6222471/268669
			$("body")
				.append('<iframe src="javascript:false;" name="' + id + '" id="' + id + '" style="display: none;"></iframe>');

			return $('#' + id);
		}
		
		function createForm(iframe) {
			var $form=$("<form />");
			var send_data=settings.send_data;
			if (send_data) {
				for(key in send_data){
					//alert(key+"="+send_data[key]);
					$("<input />")
						.attr("type", "hidden")
						.attr("name", key)
						.val(send_data[key])
						.appendTo($form);
				}
			};
			return $form
				.attr({
					method: "post",
					action: settings.action,
					enctype: "multipart/form-data",
					target: iframe[0].name
				})
				.hide()
				.appendTo("body");
		}
	};
})(jQuery);

var interval;
function applyAjaxFileUpload(element,send_data,action){
  $(element).AjaxFileUpload({
      send_data:send_data,
      action:action,//用于文件上传的服务器端请求地址
      onChange: function(filename) {
        // Create a span element to notify the user of an upload in progress
        var $span = $("<span />").attr("class", $(this).attr("id")).text("Uploading").insertAfter($(this));
        $(this).remove();
        interval = window.setInterval(function() {
          var text = $span.text();
          if (text.length < 13) {
            $span.text(text + ".");
          } else {
            $span.text("Uploading");
          }
        }, 200);
      },
      onSubmit:function(filename){
          return true;
      },
      onComplete: function(filename, response) {
        // alert(filename);
        // alert(response.img_path);
        window.clearInterval(interval);
        var $span = $("span." + $(this).attr("id")).text(filename + " ");
        if (response && filename) {
          $("#old_" + $(this).attr("id")).val(response.img_path);
          $("#img_" + $(this).attr("id")).attr('src',response.thumb_img);
          if ($('#thumbnail').length)
            $("#thumbnail").attr('href',response.http_img);
          if ($('a[href="#clear_img"]').length)
            $('a[href="#clear_img"]').show();
        }
        $fileInput = $("<input />")
          .attr({
            type: "file",
            name: $(this).attr("name"),
            id: $(this).attr("id")
          });
        if (typeof(response.error) === "string") {
          $span.replaceWith($fileInput);
          applyAjaxFileUpload($fileInput,send_data,action);
          alert(response.error);
          return;
        }
        $span.replaceWith($fileInput);
        applyAjaxFileUpload($fileInput,send_data,action);
      }
  });
}

//清除原圖.
function clear_img(obj,action,default_img){
  if (confirm('您確定要刪除該圖片嗎?')) {
    var element_id = obj.attr('tag');
    var element_value = $('#old_'+element_id).val();
    if (element_value) {
      $.get(action,{'path':element_value}, function(data) {
        if(data && parseInt(data)==1){
          $("#img_" + element_id).attr('src',default_img);
          if ($('#thumbnail').length)
            $("#thumbnail").attr('href',default_img);
          $("#old_" + element_id).val('');
          $('a[href="#clear_img"]').hide();
          return;
        }
        alert('Clear Image Ajax Is Error!');
      });
    };
  };
}
